package com.zyy.joseata.interceptor;

import com.zyy.joseata.constant.TxEventTypeConst;
import com.zyy.joseata.socket.SocketClient;
import com.zyy.joseata.util.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.support.DefaultTransactionStatus;

import javax.sql.DataSource;

/**
 * @author zhangyy
 */
@Slf4j
public class TransManagerInterceptor extends DataSourceTransactionManager {

    private SocketClient socketClient;

    public void setSocketClient(SocketClient socketClient){
        this.socketClient = socketClient;
    }

    public TransManagerInterceptor(DataSource dataSource){
        super(dataSource);
    }

    @Override
    protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException{

        log.info("事务执行前的处理.....使用log");
        if(ThreadLocalUtil.getTxId() != null){
            socketClient.send(TxEventTypeConst.RM_TX_BEGIN);
        }
        super.doBegin(transaction,definition);
    }

    @Override
    protected void doCommit(DefaultTransactionStatus status) throws TransactionException {
        super.doCommit(status);
        if(ThreadLocalUtil.getTxId() != null) {
            socketClient.send(TxEventTypeConst.RM_TX_COMMIT);
        }
        log.info("事务提交后的处理.....使用log");
    }

    @Override
    protected  void doRollback(DefaultTransactionStatus status) throws TransactionException {
        super.doRollback(status);
        if(ThreadLocalUtil.getTxId() != null) {
            socketClient.send(TxEventTypeConst.RM_TX_ROLLBACK);
        }
        log.info("事务回滚后的处理......使用log");
    }
}

